import React from 'react'
import Const from "../Const";
import ChatPanel from "./ChatPanel";
import PixelPanel from "./PixelPanel";
import {connect} from "react-redux";

/**
 * 名称：键盘按键监听
 * 创建人：袁泉
 * 创建时间：2021年08月30日20:18:03
 */
class Keymap extends React.Component {
    state = {
        moveX: 0,
        handleDragIng: false,
        treeWidth: 200,
        initTreeWidth: 200,

    }
    editorWarp = null;

    //组件被render之后调用
    componentDidMount() {
        document.addEventListener('keydown', this.onKeyDown);

    }

    componentWillUnmount() {
        document.removeEventListener('keydown', this.onKeyDown);
    }

    //上下左右方向控制
    ctrlEvent = (keycode) => {
        let {selectPoint, pixelData} = this.props;
        let {x, y, color} = selectPoint;
        if (!selectPoint) return null;
        let targetSelectPoint = null;
        this.props.deleteHColorByXy(x, y);
        switch (keycode) {
            case 38://上
                x--;
                break;
            case 39://右
                y++;
                break;
            case 40://下
                x++
                break;
            case 37://左
                y--
                break;
        }
        targetSelectPoint = pixelData[x][y];
        this.props.setSelectPoint(targetSelectPoint);
        this.props.addHColorByXy(x, y, 'red');

        // //上
        // 38: this.ctrlEvent,
        //     //右
        //     39: this.ctrlEvent,
        //     //下
        //     40: this.ctrlEvent,
        //     //左
        //     37: this.ctrlEvent,
    }

    onKeyDown = (e) => {

        let event = {
            //上
            38: this.ctrlEvent,
            //右
            39: this.ctrlEvent,
            //下
            40: this.ctrlEvent,
            //左
            37: this.ctrlEvent,
            13: function () {
                alert('发送消息');
            }
        }
        let keycode = e.keyCode;
        event[keycode] && event[keycode](keycode);

        console.log(keycode)
        return false;

    }

    render() {
        return (
            <div className={this.props.className} style={this.props.style}>
                {this.props.children}
            </div>
        )
    }
}

export default connect(
    (state, props) => {
        return {...state};
    },
    (dispatch) => {
        return {
            deleteHColorByXy(x, y) {
                dispatch({
                    type: 'deleteHColorByXy',
                    data: {x, y}
                })
            },
            addHColorByXy(x, y, color) {
                dispatch({
                    type: 'addHColorByXy',
                    data: {x, y, color}
                })
            },
            setSelectPoint(point) {
                dispatch({
                    type: 'setSelectPoint',
                    data: point
                })
            },
        };
    })(Keymap);
